package org.secur.eave.ui

import android.annotation.SuppressLint
import android.content.Intent
import android.os.Bundle
import android.os.Handler
import android.os.Looper
import android.util.Log
import android.widget.Toast
import androidx.appcompat.app.AppCompatActivity

import com.github.shadowsocks.databinding.ActivitySplashBinding
import com.google.gson.Gson
import org.secur.eave.MainActivity
import org.secur.eave.dao.StealthServer
import org.secur.eave.util.BaseUtil.Companion.convertStealthServer
import org.secur.eave.util.BaseUtil.Companion.fetchStealthLinkResult
import org.secur.eave.util.MMKVUtil
import org.secur.eave.view.Progress
@SuppressLint("CustomSplashScreen")
class SplashActivity : AppCompatActivity() {
	private lateinit var bin: ActivitySplashBinding
	
	// 用于标志进度条是否已完成
	private var isProgressComplete = false
	// 用于标志请求是否已完成
	private var isRequestComplete = false
	
	@SuppressLint("LogNotTimber")
	override fun onCreate(savedInstanceState: Bundle?) {
		super.onCreate(savedInstanceState)
		bin = ActivitySplashBinding.inflate(layoutInflater)
		setContentView(bin.root)
		
		// 设置进度条
		bin.progress.setProgress(Progress(0, "#2667DE", "#f3f3f3"))
		bin.progress.animateProgress(2000)
		
		val startTime = System.currentTimeMillis()
		
		// 启动网络请求
		fetchStealthLinkResult(
			onSuccess = { result ->
				isRequestComplete = true
				Log.d("xianban", "$result")
				val endTime = System.currentTimeMillis()
				val jsonData = try {
					Gson().toJson(result[0])
				} catch (e: Exception) {
					Log.e("SplashActivity", "JSON conversion error: ${e.message}", e)
					""
				}
				val convertStealthServer =
					convertStealthServer(Gson().fromJson(jsonData, StealthServer::class.java))
				MMKVUtil.saveStringValue(convertStealthServer)
				
				// 开始过渡到 MainActivity
				start(millis = 2000 - (endTime - startTime), data = jsonData)
			},
			onFailure = { throwable ->
				isRequestComplete = true
				start(millis = 2000)
				Log.d("xianban: ", "${throwable.message}")
			}
		)
		
		// 设置一个延迟，标记进度条完成
		Handler(Looper.getMainLooper()).postDelayed({
			isProgressComplete = true
			checkAndProceed()
		}, 2000)
	}
	
	// 检查进度条和请求的状态
	private fun checkAndProceed() {
		if (isProgressComplete && isRequestComplete) {
			// 如果两者都完成，继续
			Intent(this@SplashActivity, MainActivity::class.java).also {
				it.putExtra("data", "")
				startActivity(it)
				finish()
			}
		} else if (isProgressComplete && !isRequestComplete) {
			// 如果进度条完成，但请求未完成，提示用户
			Toast.makeText(this, "Loading... Please wait.", Toast.LENGTH_SHORT).show()
		}
	}
	
	private fun start(millis: Long, data: String = "") {
		Handler(Looper.getMainLooper()).postDelayed({
			if (isRequestComplete) {
				Intent(this@SplashActivity, MainActivity::class.java).also {
					it.putExtra("data", data)
					startActivity(it)
					finish()
				}
			} else {
				checkAndProceed()
			}
		}, millis)
	}
}

